package com.example.springboot_test;

import cn.hutool.core.bean.BeanUtil;
import com.example.springboot_test.entity.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
@RestController
@CrossOrigin
public class SpringbootTestApplication {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setName("张三" + i);
            user.setAge(10 + i);
            list.add(user);
        }

        SpringApplication.run(SpringbootTestApplication.class, args);
    }


    @GetMapping("/version")
    public String test() {
        return "v3.1.0";
    }


    private static final List<User> list = new ArrayList<>();


    @PostMapping("/list")
    public List<User> list() {

        return list;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable("id") Integer id) {
        User user1 = list.stream().filter(user -> {
            return user.getId() == id;
        }).collect(Collectors.toList()).get(0);
        return user1;
    }

    @PostMapping("/update")
    public List<User> update(@RequestBody User user) {
        for (User user1 : list) {
            if (user1.getId() == user.getId()) {
                BeanUtil.copyProperties(user, user1);
            }
        }
        return list;
    }

    @PostMapping("/add")
    public List<User> add(@RequestBody User user) {
        list.add(user);
        return list;
    }

    @DeleteMapping("/{id}")
    public List<User> remove(@PathVariable("id") Integer id) {
        list.remove(list.get(id));
        return list;
    }


}
